const { ObjectId } = require("mongodb");
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://localhost:27017/";

/* 通用的获取collection连接 */
function getCollection(dbName, collectionName) {
  return new Promise((resolve, reject) => {
    /* 尝试连接数据库 需要时间 必是异步 */
    MongoClient.connect(url, function (err, conn) {
      if (err) {
        resolve({
          msg: "连接MongoDB数据服务失败",
          err,
          // collection:undefined
          // conn:undefined
        });
      } else {
        const dbObj = conn.db(dbName);

        const collection = dbObj.collection(collectionName);
        resolve({
          msg: "成功获取collection连接",
          // err:undefined,
          collection,
          conn,
        });
      }
    });
  });
}

/* 通用插入数据 */
function doCreate(dbName, collectionName, dataObj) {
  return new Promise(async (resolve, reject) => {
    // 尝试获取collectrion连接
    const { err, collection, conn } = await getCollection(
      dbName,
      collectionName
    );

    /* 如果获取collection失败 */
    if (err) {
      resolve({ err, msg: "连接数据库失败" });
    } 
    
    else {
      collection.insertOne(dataObj, function (err, res) {
        // 释放数据库连接
        conn.close();

        // 将操作信息如实返回
        resolve({
          err,
          res,
          msg: err ? "添加数据失败" : "添加数据成功",
        });
      });
    }
    
  });
}

/* 
通用查询数据 
queryCondition 查询条件对象
*/
function doRetrieve(dbName, collectionName, queryCondition) {
  return new Promise(async (resolve, reject) => {
    // 尝试获取collectrion连接
    const { err, collection, conn } = await getCollection(
      dbName,
      collectionName
    );

    /* 如果获取collection失败 */
    if (err) {
      resolve({ err, msg: "连接数据库失败" });
    } else {
      collection
        .find(queryCondition) //{username:"heige",password:"123456"}
        .toArray(function (err, arr) {
          conn.close();
          resolve({
            err,
            arr,
          });
        });
    }
  });
}

/* 通用数据更新 */
function doUpdate(dbName, collectionName, id, dataObj) {
  return new Promise(async (resolve, reject) => {
    // 尝试获取collectrion连接
    const { err, collection, conn } = await getCollection(
      dbName,
      collectionName
    );

    /* 如果获取collection失败 */
    if (err) {
      resolve({ err, msg: "连接数据库失败" });
    } else {
      collection.updateOne(
        { _id: new ObjectId(id) },
        { $set: dataObj },
        function (err, result) {
          conn.close();
          resolve({
            err,
            result,
            msg: err ? "更新数据失败" : "更新数据成功",
          });
        }
      );
    }
  });
}

module.exports = {
  doCreate,
  doRetrieve,
  doUpdate,
};
